/**
* Class to manage a select from a table to be executed in the Servlet
* This function works like:
* query=SELECT CODE, DESCRIPTION FROM PROJECTS
* fields=code,description
* An example of the call is:
* http://localhost:3141/idbcrownINServer/idbcrownINServer?action=SELECT_FROM&query=select%20code,%20name%20from%20users&fields=USER,NAME
*
* Project: idbCrownInServer
* Author:  TM
* Date:    05/04/2013
*
* History
* ------------------
* 05/04/2013 - TM - Initial version.
*/
 
 
package Functions;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import Application.*;
import DataModel.*;

public class select_from extends genericFunction
{
    /** Constants */
    protected String SEP_COL;
    protected String SEP_ROW;
    /** Class attributes */
    protected libSQLUtil sqlUtil;
    /** Application support */
    protected static libApplication appSupport;


     /** Constructor  */
    public select_from(HttpServletRequest _request, HttpServletResponse _response) throws IOException, ServletException
    {
       super(_request, _response);
       appSupport = libApplication.getInstance();
       SEP_COL = appSupport.getSeparatorForColumns(); 
       SEP_ROW = appSupport.getSeparatorForRows();
    }
    
    /** Execute function */
    public String execute()
    {
      String     result   = "";
      String     query    = getRequest().getParameter("query");
      String     varsMsg  = getRequest().getParameter("fields");
      String[]   vars     = varsMsg.split(",");      
      Object[][] rows;
      
      try
      {
        sqlUtil  = libSQLUtil.getInstance();
        rows     = sqlUtil.select(query);
        
        result = (rows != null) ? getColumnsAndValues(rows, vars) : "-1";
        
        if (result == null)
           sendError();
        else  
           sendResponse(result);
      }
      catch(Exception ex)
      {
        sendError(ex);
      }
      
      return result;
    }
    
    /** Create a single string with all results obtained from a query */
    protected String getColumnsAndValues(Object[][] rows, String[] vars)
    {
       String   result = "";
       String[] cols   = new String[vars.length];

       for (int k=0; k<vars.length; k++)
         cols[k] = vars[k]+"=";

       for (int i=0; i<rows.length - 1; i++)
       {
         Object[] row = rows[i]; //Columns
         for (int j=0; j<row.length; j++)
           cols[j] += row[j]+SEP_ROW;
       }
       
       //Last row
       Object[] row = rows[rows.length - 1];
       for (int j=0; j<row.length; j++)
         cols[j] += row[j];
       
       //Gathering all rows and columns
       for (int k=0; k<cols.length - 1; k++)
         result += cols[k]+SEP_COL;
       
       //Last column
       result += cols[cols.length - 1];
       
       return result;
    }
}